package com.tea.config.security;

import com.tea.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@Configuration
@Slf4j
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private SecurityProperties securityProperties;

    // 最终使用的白名单列表
    private final List<String> whiteList = new ArrayList<>();

    @PostConstruct
    public void init() {
        // 从配置属性中获取白名单
        List<String> configuredUrls = securityProperties.getWhitelist().getUrls();
        if (configuredUrls != null && !configuredUrls.isEmpty()) {
            whiteList.addAll(configuredUrls);
            log.info("✅ 安全白名单配置已加载: {}", whiteList);
        } else {
            log.warn("⚠️ 警告: 配置文件中未找到白名单配置 tea.security.whitelist.urls");
        }
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        log.info("🔒 配置Spring Security规则，白名单路径: {}", whiteList);

        http
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 将配置文件中的白名单路径添加到permitAll
                .antMatchers(whiteList.toArray(new String[0])).permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    public JwtAuthenticationFilter jwtAuthenticationFilter() {
        return new JwtAuthenticationFilter(jwtUtils, whiteList);
    }
}

